import { SignJWT, jwtVerify } from 'jose'

const JWT_SECRET = process.env.JWT_SECRET || 'vertu-health-management-system-super-secret-jwt-key-2024'
const JWT_EXPIRES_IN = '7d'

// 将字符串密钥转换为 Uint8Array
const secret = new TextEncoder().encode(JWT_SECRET)

export interface JWTPayload {
  userId: string
  username: string
  iat?: number
  exp?: number
}

export async function signJWT(payload: Omit<JWTPayload, 'iat' | 'exp'>): Promise<string> {
  try {
    const jwt = await new SignJWT(payload)
      .setProtectedHeader({ alg: 'HS256' })
      .setIssuedAt()
      .setExpirationTime(JWT_EXPIRES_IN)
      .sign(secret)
    
    return jwt
  } catch (error) {
    console.error('JWT signing failed:', error)
    throw new Error('Failed to sign JWT')
  }
}

export async function verifyJWT(token: string): Promise<JWTPayload | null> {
  try {
    const { payload } = await jwtVerify(token, secret)
    return payload as unknown as JWTPayload
  } catch (error) {
    console.error('JWT verification failed:', error)
    return null
  }
}

export function decodeJWT(token: string): JWTPayload | null {
  try {
    // 简单解码 JWT payload（不验证签名）
    const parts = token.split('.')
    if (parts.length !== 3) {
      return null
    }
    
    const payload = JSON.parse(atob(parts[1]))
    return payload as JWTPayload
  } catch (error) {
    console.error('JWT decode failed:', error)
    return null
  }
}